package com.example.cursor.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cursor.entity.Student;
import com.example.cursor.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 创建学生
    @PostMapping
    public ResponseEntity<Student> create(@RequestBody Student student) {
        studentService.save(student);
        return ResponseEntity.ok(student);
    }

    // 根据ID查询学生
    @GetMapping("/{id}")
    public ResponseEntity<Student> getById(@PathVariable Long id) {
        return ResponseEntity.ok(studentService.getById(id));
    }

    // 分页查询学生列表
    @GetMapping
    public ResponseEntity<Page<Student>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        
        Page<Student> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Student::getName, name);
        }
        
        return ResponseEntity.ok(studentService.page(pageParam, queryWrapper));
    }

    // 更新学生信息
    @PutMapping("/{id}")
    public ResponseEntity<Student> update(@PathVariable Long id, @RequestBody Student student) {
        student.setId(id);
        studentService.updateById(student);
        return ResponseEntity.ok(student);
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        studentService.removeById(id);
        return ResponseEntity.ok().build();
    }
} 